import rarfile
import zipfile
import tarfile
import os


def uncompress(src_file, dest_dir):
    """解压各种类型的压缩包
    :param src_file: 你要解压的压缩包文件
    :type src_file: file
    :param dest_dir: 你要解压到的目标路径
    :type dest_dir: str
    """
    file_name, file_type = os.path.splitext(src_file)
    try:
        if file_type == '.zip':
            # 需要安装zip包：pip install zipp
            zip_file = zipfile.ZipFile(src_file)
            for names in zip_file.namelist():
                zip_file.extract(names, dest_dir)
            zip_file.close()

        elif file_type == '.rar':
            pass_wd='changeway'
            rf = rarfile.RarFile(src_file)
            if rf.needs_password():
                rf.extractall(dest_dir, pwd=pass_wd)
            else:
                print("RAR file doesn't need password.")
                rf.extractall(dest_dir, pwd=pass_wd)
            rf.close()

        else:
            # file_type == '.tgz' or file_type == '.tar' or file_type == '.gz'
            # Python自带tarfile模块
            tar = tarfile.open(fileobj=src_file)
            for name in tar.getnames():
                tar.extract(name, dest_dir)
            tar.close()

    except Exception as ex:
        print(ex)

def find_files(directory):
    file_paths = []
    for root, directories, files in os.walk(directory):
        for file in files:
          if file.endswith(('.rar', '.zip', '.tar')):
              file_paths.append(os.path.join(root, file))
    return file_paths  
    
if __name__ == '__main__':
    dest_dir = './out/'
    directory_path = './input/'
    file_paths = find_files(directory_path)
    for file_path in file_paths:
      uncompress(file_path,dest_dir)

  
